import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image,ScrollView ,RichText} from '@tarojs/components'
import { connect } from 'react-redux'
import { getTurntable, drawTurntable, shareTurntable,getQualifications } from '@/api/luck'
import classnames from 'classnames'
import { IS_USERINFO } from '@/store/user/action-types'
import parse from 'mini-html-parser2'
const redpacketImg = 'https://static3.jekunauto.com/img/others/redpacket-img.png'

import './index.scss'
interface State {
  title: string
  activityId: number | string
  bgPath: string
  remainDrawCount: number
  LotteryData: any
  activedId: string
  prizeId: any
  times: number
  actTimes: number
  isRolling: boolean
  turnTime: number
  accelerate: number
  isOpened: boolean
  lightNumber: number
  isShareAddTimes: number
	tabIndex: number
	couponList:any
	redPacketList:any
	rewardOpened:boolean
	ruleOpened:boolean
	tipsOpened:boolean
	resultOpened:boolean
	rule:string
}
//抽奖转盘灯数量
const light = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

@connect<any>(({ user, car }) => ({ user, car }))
export default class Index extends Component {
  $instance = getCurrentInstance();
  timer: any
  begin: NodeJS.Timeout
  lightTime: NodeJS.Timeout

  constructor (props) {
    super(props)
    this.timer;
    this.state = {
			tabIndex: 1,
      title: '转盘抽奖',//标题
      activityId: '',//活动id
      bgPath: '',//背景图
      remainDrawCount: 1,//抽奖剩余次数
      isShareAddTimes: 0,//是否分享可以增加抽奖机会
      LotteryData: [],//奖品
			rule:'',
      activedId: '', // 被选中的格子的ID
      prizeId: null,// 中奖ID,indexKey
      times: 0,// 获得prizeId之后计算出的动画次数
      actTimes: 0, // 当前动画次数
      isRolling: false,// 是否正在抽奖
      turnTime: 40,// 初始速度
      accelerate: 8,//加速度
      isOpened: false,// 中奖弹窗是否显示
      lightNumber: 0,// 抽奖灯循环切换 参数：0/1
			rewardOpened:false,
			ruleOpened:false,
			tipsOpened:false,
			resultOpened:true,
			redPacketList:[],
			couponList:[]
    }
  }

  state: State


  UNSAFE_componentWillMount() { }
  componentDidMount() {
    // 抽奖转盘闪烁效果
    this.lightTime = setInterval(() => {
      const { lightNumber } = this.state
      this.setState({
        lightNumber: lightNumber == 0 ? 1 : 0
      })
    }, 500)
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentDidShow() {
    // 获取活动id
    const { activityId } = this.$instance.router.params
    this.setState({
      activityId
    }, () => {
      // 获取抽奖详情
      this.getTurntable()
    })
  }
  componentWillUnmount() {
    //清除定时器
    clearInterval(this.begin)
    clearInterval(this.lightTime)
  }

  // 获取抽奖详情
  async getTurntable() {
    const { activityId } = this.state
    await getTurntable({ activityId }).then((res) => {
      const { data: { data } } = res
      Taro.setNavigationBarTitle({
        title: data.title
      })
      this.setState({
        title: data.title,
        bgPath: data.bgPath,
        LotteryData: data.award,
        remainDrawCount: data.remainDrawCount,
        isShareAddTimes: data.isShareAddTimes,
				rule:data.rule,
      })
    })
  }

	// 获取奖品详情
   getQualifications() {
    const { activityId } = this.state
		this.setRewradToggle('isOpened',false)
		console.log('activityId',activityId)
		Taro.showLoading({
			title: '加载中'
		})
    getQualifications({ activityId }).then((res) => {
      const { data: { data } } = res
      this.setState({
        couponList: data.couponList,
        redPacketList: data.redPacketList
      },()=>{
				this.setRewradToggle('rewardOpened',true)
				Taro.hideLoading()
			})

    })
  }

  //设置分享
  onShareAppMessage(msg) {
    const USERINFO = Taro.getStorageSync(IS_USERINFO)
    const STORECODE = Taro.getStorageSync('STORECODE')
    const { title, activityId } = this.state
    // 分享时有授权登录，门店信息 才调起接口增加次数
    if (USERINFO && STORECODE) {
      // 分享接口 增加抽奖次数
      shareTurntable({ activityId }).then(() => {
      })
    }
    return {
      title,
      path: `/pages/luck/index/index?activityId=${activityId}`
    }
  }

  // 点击抽奖
  async handleBegin() {
    const { car: { carInfo: { currentCar } } } = this.props
    const { isRolling, remainDrawCount, activityId } = this.state

    // this.state.isRolling为false的时候才能开始抽,不然会重复，报错。
    // if (remainDrawCount <= 0) {
    //   return Taro.showModal({
    //     title: '',
    //     content: '已没有抽奖次数',
    //     showCancel: false,
    //   })
    // }

		if(remainDrawCount <= 0){
			this.setState({
				tipsOpened:true
			})
			return
		}

    if (!isRolling) {
      // 点击抽奖之后，可以将于九宫格有关的状态都还原默认。然后
      await drawTurntable({ activityId }).then((res) => {
        const { data: { data } } = res
        this.setState({
          // activedId: '',
          prizeId: null,
          times: 0,
          actTimes: 0,
          isRolling: true,
          turnTime: 40,
          remainDrawCount: remainDrawCount - 1
        }, () => {
          // 状态还原再开始真正的抽奖  传入中奖位置
          this.handlePlay(Number(data.position) - 1)
        })
      })
    }
  }

  //开始抽奖
  async handlePlay(prizeId) {
    let { turnTime, actTimes } = this.state
    //此处可以调用后台。一般抽奖都是后台返回前端
    // 中将indexKey ，可随机，可自己设定，我这里暂且定为5
    // let prizeId = 5
    // 随机算出一个动画执行的最小次数，这里可以随机变更数值，按自己的需求来
    let times = 25
    this.setState({
      prizeId,
      times
      // activedId: 0,    //转的起始位置
    })

    // 抽奖正式开始
    this.begin = setInterval(() => Fn(), turnTime)
    const Fn = () => {
      let num;
      if (this.state.activedId === this.state.prizeId && actTimes > this.state.times) {
        // 符合上述所有条件时才是中奖的时候，两个ID相同并且动画执行的次数大于(或等于也行)设定的最小次数
        clearInterval(this.begin)
        //将抽奖状态转为false。
        this.setState({
          isRolling: false
        })
        //这里可以加一些modol等一些东西。转盘结束，告诉用户此次抽奖中否
        this.setState({
          isOpened: true,
        })
        return
      }
      // 以下是动画执行时对id的判断，每40秒执行一次
      if (this.state.activedId === '') {
        //从0开始转动
        num = 0
        this.setState({
          activedId: num
        })
      } else {
        num = this.state.activedId
        //从0开始转动，转到到7的时候，也就意味是最后一个，将num置为0.重新开始转
        if (num === 7) {
          num = 0
          this.setState({
            activedId: num
          })
        } else {
          num = num + 1
          this.setState({
            activedId: num
          })
        }
      }

      // 设置加速度，缓速
      let accelerate
      if (actTimes >= 30) {
        accelerate = 50
      } else if (actTimes < 30 && actTimes >= 25) {
        accelerate = 12
      } else {
        accelerate = 8
      }

      this.setState({
        actTimes: actTimes += 1,
        turnTime: turnTime += accelerate,
        // accelerate
      }, () => {
        const { turnTime } = this.state
        clearInterval(this.begin);
        this.begin = setInterval(Fn, turnTime)
      })
    }
  }

	goToDetails(list) {
		console.log('list',list)
		let url =  `/pages/coupon/details/index?id=${list.couponItemId}&tabType=${1}&belongStoreCode=${list.storeCode}`
		Taro.navigateTo({
			url
		})

	}

	  // 用户红包类型列表
		userRedpacketListView() {
			const {
				redPacketList,
			} = this.state
			return (
				<View className='redpacket-bd'>
					<ScrollView scrollY className='tab-cont'>

						<View className='tab-cont-item'>
							{
							 redPacketList.map(list => {
									return (
										<View key={list.id} className={classnames('rbtab-cont-item-li')}>
											{list.sendStatus === 0 ? <View className='expireSoon-tips'>发送中</View> : null}
											<Image className='img' src={redpacketImg}></Image>
											<View className={classnames('cont')}>
												<View className='rb-price'>￥{list.amount}</View>
												<View className='text'>{list.storeName}可用</View>
												<View className='text'>{`${list.startDate}~${list.endDate}`}</View>
											</View>
										</View>
									)
								})
							}
						</View>
						<View className='scroll-bt-tips'>没有更多记录啦</View>
					</ScrollView>
				</View>
			)
		}

	userCouponListView() {
		const { couponList} = this.state
		return (
		<View  className='coupon-bd'>
				{
					couponList && couponList.map(list => {
						return <View>
							<View className='coupon-list'>
								<View className='coupon-item'>
									<View className='coupon-item__left'>
										<View className='coupon'>
											<Image src={list.awardImgUrl} className='coupon-item__img'></Image>
										</View>
									</View>
									<View className='coupon-item__right'>
										<View className='coupon-item__name'>{list.awardName}</View>
										<View className='coupon-item__shop'>{list.storeName}可用</View>
										<View className='coupon-item__date'>{list.startDate}~{list.endDate}</View>
										<View className='use-btn__warp'>
											{
												list.couponStatus == 0 ? <View className='use-btn' onClick={()=>this.goToDetails(list)}>去使用</View> : <View className='use-txt'>{list.couponStatusLabel}</View>
											}

										</View>
									</View>

								</View>
							</View>
						</View>
					}
				)
			}
			<View className='scroll-bt-tips'>没有更多记录啦</View>
		</View>

		)

	}

	setRewradToggle=(key,boolean)=>{
		this.setState({
			[key]:boolean
		})
	}

	tabData(e){
		this.setState({
			tabIndex:e
		})
	}

	// 活动规则
  ruleInfo() {
    const { rule } = this.state
		let alipayNode = []
    if (rule) {
      parse(rule, (err, nodes) => {
        console.log('err', err)
        if (!err) {
          alipayNode = nodes
          console.log(alipayNode)
        }
      })
    }
    return (
			<View className='self-dialog'>
				<View className='self-mask' onClick={()=>this.setRewradToggle('ruleOpened',false)}></View>
				<View className='self-content'>
					<View className='self-title'>
						活动规则
					</View>
					<View className='rule-box'>
						<View>
							{
                process.env.TARO_ENV === 'weapp' ? <RichText nodes={rule} /> : <RichText nodes={alipayNode} />
              }
						</View>
					</View>

				</View>
			</View>
		)
  }

	// 活动规则
  rewardInfo() {
    const { tabIndex} = this.state
    return (
			<View className='self-dialog'>
				<View className='self-mask' onClick={()=>this.setRewradToggle('rewardOpened',false)}></View>
				<View className='self-content'>
					<View className='self-title'>
						我的奖品
					</View>
					<View className='coupon-index'>
          <View className='fixed-top'>
            <View className='tab-item'>
              <View
                onClick={() => {
                  this.tabData(1)
                }}
                className={classnames(
                  'tab-li',
                  tabIndex === 1 && 'act'
                )}
              >
                <View className='tab-li-text'>卡券</View>
              </View>
              <View
                onClick={() => {
                  this.tabData(2)
                }}
                className={classnames(
                  'tab-li',
                  tabIndex === 2 && 'act'
                )}
              >
                <View className='tab-li-text'>红包</View>
              </View>
            </View>
          </View>
          {tabIndex === 1 && this.userCouponListView()}
					{tabIndex === 2 && this.userRedpacketListView()}
        </View>
				</View>
			</View>
		)
  }

	// 提示内容
  tipsInfo() {
    const {  } = this.state
    return (
			<View className='self-dialog'>
				<View className='self-mask' ></View>
				<View className='self-content self-content-2'>
					<View className='tips-content'>
						<View className='tips-close' onClick={()=>this.setRewradToggle('tipsOpened',false)}></View>
						<View className='tips-txtbox'>抱歉，您暂无参与资格哦~</View>
					</View>
				</View>
			</View>
		)
  }
	handleSeek(){
		this.setState({
			isOpened:false,
			rewardOpened:true,
		})
	}

		// 中奖结果提示内容
		resultInfo() {
			let {LotteryData,prizeId } = this.state
			return (
				<View className='self-dialog'>
					<View className='self-mask' ></View>
					<View className='self-content self-content-2'>
						<View className='tips-content result-content'>
							<View className='tips-close' onClick={()=>this.setRewradToggle('isOpened',false)}></View>
							<View className='self-combox'>
									<View className='result-imgbox'>
										<Image src={LotteryData[prizeId].path}  mode="aspectFit" className='img'></Image>
									</View>
									<View className='result-txtbox'>
										<View className='mb10'>恭喜您获得</View>
										<View>{LotteryData[prizeId].name}</View>
									</View>
									<View className='result-seek-btn' onClick={()=>this.getQualifications()}>
										去查看
									</View>
							</View>
						</View>
					</View>
				</View>
			)
		}

  render() {
    const { resultOpened,tipsOpened,ruleOpened,rewardOpened,activityId, bgPath, remainDrawCount, LotteryData, activedId, isOpened, prizeId, isRolling, lightNumber, isShareAddTimes } = this.state;
    return (
      <View className="body" style={{ backgroundImage: `url(${bgPath})` }}>
        <View className="lottery_head">
          <View className="lottery_head_btn" onClick={()=>this.setRewradToggle('ruleOpened',true)} > <Image className='btn-ico' src='https://static3.jekunauto.com/img/luck/title_1.png' mode='widthFix' /> 活动规则</View>
          <View className="lottery_head_btn" onClick={()=>this.getQualifications()}><Image className='btn-ico' src='https://static3.jekunauto.com/img/luck/title_2.png' mode='widthFix' /> 我的奖品</View>
        </View>
				{
					remainDrawCount == 0 ? <View className='count-box'>暂无抽奖机会</View> : <View className='count-box'>您有{remainDrawCount}次抽奖机会</View>
				}

        {/* 抽奖大转盘 */}
        {LotteryData && LotteryData.length > 0 &&
          <View className='lottery_box'>
            {/* 4边转灯 */}
            <View className="lottery_box_border_top">
              {
                light.map((val, idx) => {
                  return <View className={`lottery_box_border_light ${idx % 2 == lightNumber ? 'light2' : ''}`}></View>
                })
              }
            </View>
            <View className="lottery_box_border_right">
              {
                light.map((val, idx) => {
                  return <View className={`lottery_box_border_light ${idx % 2 == lightNumber ? 'light2' : ''}`}></View>
                })
              }
            </View>
            <View className="lottery_box_border_bottom">
              {
                light.map((val, idx) => {
                  return <View className={`lottery_box_border_light ${idx % 2 == lightNumber ? '' : 'light2'}`}></View>
                })
              }
            </View>
            <View className="lottery_box_border_left">
              {
                light.map((val, idx) => {
                  return <View className={`lottery_box_border_light ${idx % 2 == lightNumber ? '' : 'light2'}`}></View>
                })
              }
            </View>
            {/* 九宫格抽奖区 */}
            <View className="lottery_box_mian">
              <View className='lottery_box_s'>
                {/* 当选中的id和indexKey相等时给加上active  isRolling==true 表示在抽奖中 */}
                <View className='lottery_box_view'  >
                  {
                    isRolling && activedId != '0' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[0].path} />
                  <View className='lottery_box_view_title'>{LotteryData[0].name}</View>
                </View>
                <View className='lottery_box_view'>
                  {
                    isRolling && activedId != '1' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[1].path} />
                  <View className='lottery_box_view_title'>{LotteryData[1].name}</View>
                </View>
                <View className='lottery_box_view'>
                  {
                    isRolling && activedId != '2' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[2].path} />
                  <View className='lottery_box_view_title'>{LotteryData[2].name}</View>
                </View>
              </View>
              <View className='lottery_box_s'>
                <View className='lottery_box_view' >
                  {
                    isRolling && activedId != '7' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[7].path} />
                  <View className='lottery_box_view_title'>{LotteryData[7].name}</View>
                </View>
                <View className={`lottery_box_view lottery_box_btn ${isRolling ? 'lottery_box_view_center_isRolling' : ''}`} onClick={() => this.handleBegin()}>
                  <View className={`lottery_box_view_center ${remainDrawCount == 0 || isRolling ? 'lottery_box_view_center_isRolling' : ''}`}>
                    {/* <View className={`lottery_box_view_center_text_b ${isRolling ? 'lottery_box_view_center_text_b_isRolling' : ''}`}>抽奖</View>
                    <View className={`lottery_box_view_center_text_s ${isRolling ? 'lottery_box_view_center_text_s_isRolling' : ''}`}>剩余{remainDrawCount}次</View> */}
                  </View>
                </View>
                <View className='lottery_box_view' >
                  {
                    isRolling && activedId != '3' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[3].path} />
                  <View className='lottery_box_view_title'>{LotteryData[3].name}</View>
                </View>
              </View>
              <View className='lottery_box_s'>
                <View className='lottery_box_view' >
                  {
                    isRolling && activedId != '6' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[6].path} />
                  <View className='lottery_box_view_title'>{LotteryData[6].name}</View>
                </View>
                <View className='lottery_box_view' >
                  {
                    isRolling && activedId != '5' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[5].path} />
                  <View className='lottery_box_view_title'>{LotteryData[5].name}</View>
                </View>
                <View className='lottery_box_view' >
                  {
                    isRolling && activedId != '4' && <View className="lottery_box_view_shadow"></View>
                  }
                  <Image className='lottery_box_view_img' src={LotteryData[4].path} />
                  <View className='lottery_box_view_title'>{LotteryData[4].name}</View>
                </View>
              </View>
            </View>
          </View>
        }

        {/* {
          isOpened && <View className="dialog">
            <View className="dialog_bg"></View>
            <View className="dialog_body">
              <View className="dialog_body_main">
                <AtIcon className="dialog_body_main_icon" value='close-circle' size='22' color='#ffffff' onClick={() => this.setState({ isOpened: false })}></AtIcon>
                <Image className="dialog_body_main_title" mode="widthFix" src={InLuck} />
                <View className="dialog_body_main_goods">
                  <View className="dialog_body_main_goods_name">获得奖品{LotteryData[prizeId].name}</View>
                  <Image className="dialog_body_main_goods_img" mode="aspectFit" src={LotteryData[prizeId].path} />
                </View>
                <View className="dialog_body_main_share">
                  <Button className="dialog_body_main_share_btn" openType='share'>
                    {
                      isShareAddTimes == 0 ? '分享好友' : '分享好友 赚抽奖机会'
                    }
                  </Button>
                </View>
              </View>
            </View>
          </View>
        } */}
				{rewardOpened && this.rewardInfo()}
				{ruleOpened && this.ruleInfo()}
				{tipsOpened && this.tipsInfo()}
				{isOpened && this.resultInfo()}
      </View>
    )
  }
}
